package com.jueling.culture.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jueling.culture.core.AbstractService;
import com.jueling.culture.dto.req.AgentVO;
import com.jueling.culture.dto.res.AgentUser;
import com.jueling.culture.dto.res.AgentUserForHover;
import com.jueling.culture.enums.YesNoEnum;
import com.jueling.culture.mapper.AgentInfoMapper;
import com.jueling.culture.mapper.AgentUserMapper;
import com.jueling.culture.model.AgentInfo;
import com.jueling.culture.model.CustUser;
import com.jueling.culture.service.AgentInfoService;
import com.jueling.culture.service.CustUserInfoService;
import com.jueling.culture.util.DateUtil;
import com.jueling.culture.util.StringUtil;
import com.jueling.culture.util.SystemUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @author linp
 * @date 2022/04/09
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AgentInfoServiceImpl extends AbstractService<AgentInfo> implements AgentInfoService {

    @Resource
    @SuppressWarnings("unused")
    private AgentInfoMapper agentInfoMapper;
    @Resource
    private AgentUserMapper agentUserMapper;
    @Resource
    private CustUserInfoService custUserInfoService;
    @Autowired
    private AgentInfoService agentInfoService;


    /**
     * 获取代理信息列表
     *
     * @param agentVO
     * @return
     */
    @Override
    public  PageInfo<AgentInfo> getAgrntList(AgentVO agentVO) {
        String custID = StringUtil.isNotEmptyStr(agentVO.getAgentId()) ? agentVO.getAgentId() : SystemUserUtil.getUserInfo().getUnderCustId();
        if(StringUtil.isEmptyStr(custID)){
            PageHelper.startPage(agentVO.getPageIndex(),agentVO.getPageSize());
            List<AgentInfo> list = agentInfoMapper.getAgentList(agentVO);
            PageInfo<AgentInfo> pageInfo = new PageInfo<>(list);
            return pageInfo;
        }
        //判断是否需要级联查询
        if (YesNoEnum.YES.getCode().equals(agentVO.getIsCascade())) {
            CustUser custUser = custUserInfoService.getCustUserInfoByCustID(custID);
            //查询下级代理人
            String custId = agentUserMapper.getLowerCustId(custUser.getCustIdAll());
            if (StringUtil.isNotEmptyStr(custId)) {
                List<String> arrayList = new ArrayList<String>();
                arrayList.addAll(Arrays.asList(custId.split(",")));
                arrayList.add(agentVO.getAgentId());
                agentVO.setAgentIdList(arrayList);
                //保留一条条件
                agentVO.setAgentId(null);
            } else {
                agentVO.setAgentId(custID);
            }
        } else {
            agentVO.setAgentId(custID);
        }
        PageHelper.startPage(agentVO.getPageIndex(),agentVO.getPageSize());
        List<AgentInfo> list = agentInfoMapper.getAgentList(agentVO);
        PageInfo<AgentInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 新增代理人
     *
     * @param agentInfo
     */
    @Override
    public void saveAgentInfo(AgentInfo agentInfo) {
        agentInfo.setCustId(agentInfoMapper.getAgentMaxId() + "");
        //获取上级代理人信息
        CustUser custUser = new CustUser();
        if (StringUtil.isNotEmptyStr(agentInfo.getTjrIdNew()) || StringUtil.isNotEmptyStr(agentInfo.getTjrId())) {
            String tjrId = StringUtil.isEmptyStr(agentInfo.getTjrIdNew()) ? agentInfo.getTjrId() : agentInfo.getTjrIdNew();
            //获取推荐人信息
            AgentInfo agentInfo1 = agentInfoMapper.selectByPrimaryKey(tjrId);
            agentInfo.setDjd(agentInfo1.getDjd() + 1);
            //获取推荐人链路
            CustUser custUserP = custUserInfoService.getCustUserInfoByCustID(StringUtil.isEmptyStr(agentInfo.getTjrIdNew()) ? agentInfo.getTjrId() : agentInfo.getTjrIdNew());
            if(custUserP != null){
                custUser.setCustId(agentInfo.getCustId());
                custUser.setCustIdAll(custUserP.getCustIdAll() + "," + agentInfo.getCustId());
                custUser.setLevels(Integer.valueOf(custUserP.getLevels()).intValue() + 1 + "");
                custUser.setCustIdP(custUserP.getCustId());
                agentInfo.setDljb(agentInfo1.getDljb() + 1);
            }else{
                custUser.setCustId(agentInfo.getCustId());
                custUser.setCustIdAll(agentInfo.getCustId());
                custUser.setCustIdP("0");
                custUser.setLevels("1");
                agentInfo.setDljb(1);
            }
            agentInfo.setTjrmc(agentInfoMapper.getAgentName(agentInfo.getTjrId()));
            if(StringUtil.isNotEmptyStr(agentInfo.getTjrIdNew())){
                agentInfo.setTjrmcNew(agentInfoMapper.getAgentName(agentInfo.getTjrIdNew()));
            }
        } else {
            custUser.setCustId(agentInfo.getCustId());
            custUser.setCustIdAll(agentInfo.getCustId());
            custUser.setCustIdP("0");
            custUser.setLevels("1");
            agentInfo.setDljb(1);
            agentInfo.setDjd(1);
        }
        if(StringUtil.isNotEmptyStr(agentInfo.getSjtjr())){
            agentInfo.setSjtjrMc(agentInfoMapper.getAgentName(agentInfo.getSjtjr()));
        }
        custUserInfoService.saveCustUserInfo(custUser);
        agentInfoMapper.insertSelective(agentInfo);
    }

    /**
     * 编辑代理人信息
     *
     * @param agentInfo
     */
    @Override
    public void updateAgentInfo(AgentInfo agentInfo) {
        //判断推荐人信息是否变更
        if (agentInfo.getTjrIdNew() != null || agentInfo.getTjrId() != null) {
            //重新获取代理人/新代理人/实际代理人名称
            agentInfo.setTjrmc(agentInfoMapper.getAgentName(agentInfo.getTjrId()));
            if(StringUtil.isNotEmptyStr(agentInfo.getTjrIdNew())){
                agentInfo.setTjrmcNew(agentInfoMapper.getAgentName(agentInfo.getTjrIdNew()));
            }
            if(StringUtil.isNotEmptyStr(agentInfo.getSjtjr())){
                agentInfo.setSjtjrMc(agentInfoMapper.getAgentName(agentInfo.getSjtjr()));
            }
        }
        //更新
        agentInfoMapper.updateAgent(agentInfo);
        //更新代理人推荐人/推荐人新/实际推荐人名称
        agentInfoMapper.updateTxrmc(agentInfo.getCustId(),agentInfo.getYhxm());
        //更新代理链路
        agentInfoService.refushAgent("linp");
    }

    /**
     * 查询代理人是否存在
     *
     * @param custId
     * @return
     */
    @Override
    public Integer checkAgent(String custId) {
        return agentInfoMapper.checkAgent(custId);
    }

    /**
     * 查询代理人列表
     *
     * @return
     */
    @Override
    public List<AgentUser> getAgentUserList() {
        String custID = SystemUserUtil.getUserInfo().getUnderCustId();
        List<AgentUser> agentUserList = agentInfoMapper.getAgentUserList(custID);
        if (StringUtil.isNotEmptyStr(custID)) {
            for (AgentUser agentUser : agentUserList) {
                if(agentUser.getId().equals(custID)){
                    agentUser.setPCustId("0");
                }
            }
            return AgentUser.parseTree(agentUserList);
        } else {
            return AgentUser.parseTree(agentUserList);
        }
    }

    /**
     * 代理人级联结构
     *
     * @return
     */
    @Override
    public List<AgentUserForHover> getAgentUserListForHover() {

        List<AgentUserForHover> agentUserList = agentInfoMapper.getAgentUserListForHover();
        AgentUserForHover agentUser = new AgentUserForHover();
        agentUser.setValue("");
        agentUser.setLabel("觉灵文化");
        List<AgentUserForHover> agentUsers = new ArrayList<>();
        agentUsers.add(agentUser);
        agentUsers.addAll(agentUserList);
        return agentUsers;
    }

    /**
     * 刷数据
     *
     * @param code
     * @return
     */
    @Override
    public Object refushAgent(String code) {
        if(!("linp").equals(code)){
            return false;
        }
        custUserInfoService.deleteAll();
        //查询推荐人为空的代理人
        List<AgentInfo> agentInfoList = agentInfoMapper.getAgentListByTjRId();
        dealData(agentInfoList);
        return true;
    }

    private void dealData(List<AgentInfo> agentInfoList) {
        for (AgentInfo agentInfo : agentInfoList) {
            //获取上级代理人信息
            CustUser custUser = new CustUser();
            if (StringUtil.isNotEmptyStr(agentInfo.getTjrIdNew()) || StringUtil.isNotEmptyStr(agentInfo.getTjrId())) {
                String tjrId = StringUtil.isEmptyStr(agentInfo.getTjrIdNew()) ? agentInfo.getTjrId() : agentInfo.getTjrIdNew();
                AgentInfo agentInfo1 = agentInfoMapper.selectByPrimaryKey(tjrId);
                //获取推荐人链路
                CustUser custUserP = custUserInfoService.getCustUserInfoByCustID(tjrId);
                if(custUserP == null){
                    custUser.setCustId(agentInfo.getCustId());
                    custUser.setCustIdAll(agentInfo.getCustId());
                    custUser.setCustIdP("0");
                    custUser.setLevels("1");
                    agentInfo.setDljb(agentInfo1.getDljb() + 1);
                }else{
                    custUser.setCustId(agentInfo.getCustId());
                    custUser.setCustIdAll(custUserP.getCustIdAll() + "," + agentInfo.getCustId());
                    custUser.setLevels(Integer.valueOf(custUserP.getLevels()).intValue() + 1 + "");
                    custUser.setCustIdP(custUserP.getCustId());
                    agentInfo.setDljb(agentInfo1.getDljb() + 1);
                }
            } else {
                custUser.setCustId(agentInfo.getCustId());
                custUser.setCustIdAll(agentInfo.getCustId());
                custUser.setCustIdP("0");
                custUser.setLevels("1");
                agentInfo.setDljb(1);
            }
            custUserInfoService.saveCustUserInfo(custUser);
        }
    }

    /**
     * 修改用户状态
     *
     * @param custId
     * @return
     */
    @Override
    public void updateAgentState(String custId) {
        agentInfoMapper.updateAgentState(custId);
    }

    /**
     * 根据查询条件查询全量数据
     *
     * @param agentVO
     * @return
     */
    @Override
    public List<List<Object>> getAllAgentData(AgentVO agentVO) {
        String custID = StringUtil.isNotEmptyStr(agentVO.getAgentId()) ? agentVO.getAgentId() : SystemUserUtil.getUserInfo().getUnderCustId();
        List<AgentInfo> list = new ArrayList<>();
        if(StringUtil.isEmptyStr(custID)){
            list = agentInfoMapper.getAgentList(agentVO);
        }else{
            //判断是否需要级联查询
            if (YesNoEnum.YES.getCode().equals(agentVO.getIsCascade())) {
                //查询下级代理人
                String custId = agentUserMapper.getLowerCustId(custID);
                if (StringUtil.isNotEmptyStr(custId)) {
                    List<String> arrayList = new ArrayList<String>();
                    arrayList.addAll(Arrays.asList(custId.split(",")));
                    arrayList.add(agentVO.getAgentId());
                    agentVO.setAgentIdList(arrayList);
                    //保留一条条件
                    agentVO.setAgentId(null);
                } else {
                    agentVO.setAgentId(custID);
                }
            } else {
                agentVO.setAgentId(custID);
            }
           list = agentInfoMapper.getAgentList(agentVO);
        }
        return formatData(list);
    }

    /**
     * 数据格式化
     * @param result
     */
    public List<List<Object>> formatData(List<AgentInfo> result){

        List<List<Object>> list = new ArrayList<>();
        int num = 0;
        //格式化数据,并填充数据
        for (AgentInfo agentInfo : result ) {
            num ++;
            List<Object> data = new ArrayList<>();
            //序号
            data.add(num);
            //数据
            data.add(agentInfo.getYhxm());
            data.add(agentInfo.getCustNo());
            data.add(agentInfo.getLxdh());
            data.add(DateUtil.dateToString(agentInfo.getDjsj(),DateUtil.FORMAT_DATETIME));
            data.add(agentInfo.getSfxnyh() == 1 ? "是" : agentInfo.getSfxnyh() == 2 ? "否" : "-");
            data.add(agentInfo.getSjtjrMc());
            data.add(dljbType(agentInfo.getDljbId()));
            data.add(stateType(agentInfo.getYhzt()));
            data.add(agentInfo.getTjrmc());
            data.add(agentInfo.getTjrmcNew());
            data.add(agentInfo.getKhhmc());
            data.add(agentInfo.getKhm());
            data.add(agentInfo.getYhkh());
            data.add(agentInfo.getShdz());
            list.add(data);
        }
        return list;
    }

    private static Object stateType(Integer state) {
        if (state == 0) {
            return "待确认";
        }
        if (state == 1) {
            return "已确认";
        }
        if (state == 2) {
            return "停用";
        }
        if (state == 3) {
            return "撤销";
        }
        return null;
    }

    private static Object dljbType(String state) {
        if(StringUtil.isEmptyStr(state)){
            return "-";
        }
        if (state.equals("jlwh0001")) {
            return "市级代理";
        }
        if (state.equals("jlwh0002")) {
            return "省级代理";
        }
        if (state.equals("jlwh0003")) {
            return "大区代理";
        }
        if (state.equals("jlwh0004")) {
            return "一星代理";
        }
        if (state.equals("jlwh0005")) {
            return "二星代理";
        }
        if (state.equals("jlwh0006")) {
            return "三星代理";
        }
        if (state.equals("jlwh0007")) {
            return "四星代理";
        }
        if (state.equals("jlwh0008")) {
            return "五星代理";
        }
        return null;
    }
}
